package com.qi.controller;

import com.qi.Utils.JWTUtils;
import com.qi.pojo.User;
import com.qi.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * @author yd
 * @version 1.0
 * @date 2020/12/29 21:18
 */
@RestController
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 生成Token
     *
     * @param user
     * @return
     */
    @GetMapping("/user/login")
    public Map<String, Object> login(User user) {
        log.info("用户名:[{}]", user.getUsername());
        log.info("密码:[{}]", user.getPassword());

        HashMap<String, Object> map = new HashMap<>();

        try {
            User userDB = userService.login(user);
            // 生成JWT令牌
            HashMap<String, String> payload = new HashMap<>();
            payload.put("id", String.valueOf(userDB.getId()));
            payload.put("username", userDB.getUsername());
            String token = JWTUtils.GetToken(payload);
            map.put("state", true);
            map.put("msg", "验证成功~");
            map.put("token", token);
        } catch (Exception e) {
            map.put("state", false);
            map.put("msg", e.getMessage());
        }
        return map;
    }

    /**
     * 验证Token
     *
     * @param token
     * @return
     */
    @RequestMapping("/test")
    public Map<String, Object> test(String token) {
        log.info("当前token为：[{}]", token);
        HashMap<String, Object> map = new HashMap<>();
        try {
            JWTUtils.verify(token);
            map.put("state", true);
            map.put("msg", "认证成功");
        } catch (Exception e) {
            map.put("state", false);
            map.put("msg", "认证失败");
            e.printStackTrace();
        }
        return map;
    }
}
